import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {ActivatedRoute} from '@angular/router';
import {GnJsonFormComponent, GnMessageService} from 'geminis-ng';
import {GnJsonUtils} from 'geminis-ng-core';
import {PlanetPortalApplication} from '@worktile/planet';

@Component({
  selector: 'gn-auth-server-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  codeToken: string;

  @ViewChild(GnJsonFormComponent, {static: true}) form: GnJsonFormComponent;
  @Output() errored = new EventEmitter();

  constructor(private httpClient: HttpClient,
              public portal: PlanetPortalApplication,
              private messageService: GnMessageService,
              private activatedRoute: ActivatedRoute) {
    this.messageService.clean();
    activatedRoute.queryParams.subscribe(queryParams => {
      if (queryParams.msg) {
        this.setError(queryParams.msg);
      }
    });
  }

  ngOnInit(): void {
    this.portal.data.loginUser.clean();
  }

  refreshCode() {
    this.httpClient.get('/resources-service/login/code', {responseType: 'text'})
      .subscribe((data: any) => {
        // this.code = data;
        // this.imageUrl = '/RESOURCES-SERVICE/login/codeImage/' + this.code;
      });
  }

  loginPwd(): void {
    this.messageService.success('登录中...');
    this.form.form.formGroup.value.codeToken = this.codeToken;

    const loginValue = GnJsonUtils.obj2FormData(this.form.form.formGroup.value);

    this.httpClient.post('/auth-server/login', loginValue, {observe: 'response'})
      .subscribe((resp: any) => {
          this.portal.data.loginUser.setValue(resp.body);
          this.portal.data.loginUser.jwt = resp.headers.get('Authorization');
          this.portal.data.loginUser.jwtExpire = resp.headers.get('Authorization-Expire');
          this.portal.data.loginUser.isLogin = true;
          this.portal.data.loginUser.save();
          this.messageService.success('登录成功，正在跳转');

          this.portal.data.siteInfo.filterMenu(this.portal.data.loginUser.authorities.map(value => value.authority));

          if (!this.portal.data.siteInfo.authSiderMenu || this.portal.data.siteInfo.authSiderMenu.length === 0) {
            this.setError('没有可访问的功能');
            return;
          }

          let item = this.portal.data.siteInfo.authSiderMenu[0];
          while (!item.router && item.subMenu && item.subMenu.length > 0) {
            item = item.subMenu[0];
          }
          const url = item.router.toString();
          this.portal.router.navigate([url]);
        },
        (error) => {
          this.setError('登录失败，' + error.error.message);
        });
  }

  private setError(message: string): void {
    this.messageService.clean();
    this.messageService.error(message);
    this.errored.emit(null);
  }

}
